import re

from django import forms
from django_redis import get_redis_connection

from apps.verifications.constants import SMS_CODE_NUMS
from .models import Users


class RegisterForm(forms.Form):
    """
    用户注册功能，form验证
    """
    username = forms.CharField(
        label='用户名', max_length=20, min_length=5,
        error_messages={
           "min_length": "用户名长度要大于5",
           "max_length": "用户名长度要小于20",
        }
    )

    password = forms.CharField(
        label='密码', max_length=20, min_length=6,
        error_messages={
            "min_length": "密码长度要大于6",
            "max_length": "密码长度要小于20",
        }
    )

    password_repeat = forms.CharField(
        label='确认密码', max_length=20, min_length=6,
        error_messages={
            "min_length": "密码长度要大于6",
            "max_length": "密码长度要小于20",
        }
    )

    mobile = forms.CharField(
        label='手机号', max_length=11, min_length=11,
        error_messages={
            "min_length": "手机号长度有误",
            "max_length": "手机号长度有误",
        }
    )

    sms_code = forms.CharField(
        label='短信验证码', max_length=SMS_CODE_NUMS, min_length=SMS_CODE_NUMS,
        error_messages={
            "min_length": "短信验证码长度有误",
            "max_length": "短信验证码长度有误",
        }
    )

    def clean_mobile(self):
        tel = self.cleaned_data.get('mobile')
        if not re.match(r'^1[3-9]\d{9}$', tel):
            raise forms.ValidationError('手机号码格式不正确')

        if Users.objects.filter(mobile=tel).exists():
            raise forms.ValidationError('手机号已注册，请重新输入')

        return tel

    def clean(self):
        clean_data = super().clean()
        passwd = clean_data.get('password')
        passwd_repeat = clean_data.get('password_repeat')

        if passwd != passwd_repeat:
            raise forms.ValidationError('两次输入的密码不一样')

        tel = clean_data.get('mobile')
        sms_text = clean_data.get('sms_code')

        # 建立redis连接
        redis_conn = get_redis_connection(alias='verify_codes')
        sms_fmt = 'sms_{}'.format(tel).encode('utf-8')
        real_sms = redis_conn.get(sms_fmt)

        if (not sms_text) or (sms_text.upper() != real_sms.decode('utf-8').upper()):
            raise forms.ValidationError('短信验证码错误')
